package Task_0106;

import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class Servlet extends HttpServlet {
    private Dao d = new Dao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //处理post请求的乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = response.getWriter();

        //接收前端数据
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        /**
         * 判断密码是否正确 并跳转页面
         */
        boolean result1 = d.login(userName, password);
        if(result1==true){
            //存值
            HttpSession session = request.getSession();
            session.setAttribute("userName", userName);
            session.setAttribute("password",password);

            //request.getRequestDispatcher("/success.html").forward(request,response);
            response.sendRedirect("/success.jsp");//跳转到登录成功页面
        }else {
            //request.getRequestDispatcher("/fail.html").forward(request,response);
            response.sendRedirect("/fail.html");//跳转到登录失败页面
        }

        /**
         * 判断用户名是否存在
         */
        /*boolean result2 = d.isExist(userName);
        if(result2==true){
            pw.println("用户名存在");
        }else {
            pw.println("用户名不存在");
        }*/

        /**
         * 根据用户名自动填充其它信息
         */
        /*User u = d.autoFill(userName);
        JSONObject jsonObject = JSONObject.fromObject(u);//Java->JSON
        pw.println(jsonObject);*/

    }
}
